package com.emsite.common.utils;

import com.emsite.common.constant.CommonConstant;
import com.emsite.common.utils.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @Description: 认证授权相关工具类
* @author lix
* @date 2018/8/20 14:47
*/
@Slf4j
public class AuthUtils {
    private static final String BASIC_ = "Basic ";

   /**
    ============================================
    * 描   述：从header 请求中的clientId/clientsecect
    * 参   数：header
    * 返回类型：String[]
    * 创 建 人：Jerry
    * 创建时间：2018/6/26 14:29
    ============================================
    */
    public static String[] extractAndDecodeHeader(String header) throws IOException {

        byte[] base64Token = header.substring(6).getBytes("UTF-8");
        byte[] decoded;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new CommonException("Failed to decode basic authentication token");
        }

        String token = new String(decoded, CommonConstant.UTF8);

        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new CommonException("Invalid basic authentication token");
        }
        return new String[]{token.substring(0, delim), token.substring(delim + 1)};
    }

    /**
     * *从header 请求中的clientId/clientsecect
     * @param request
     * @throws IOException
     */
    public static String[] extractAndDecodeHeader(HttpServletRequest request) throws IOException {
        String header = request.getHeader("Authorization");

        if (header == null || !header.startsWith(BASIC_)) {
            throw new CommonException("请求头中client信息为空");
        }

        return extractAndDecodeHeader(header);
    }
    /**
     * *从header 请求中的clientId/clientsecect
     * @throws IOException
     */
    public static String[] extractAndDecodeHeader(ServerHttpRequest request) throws IOException {
        String header = request.getHeaders().getFirst("Authorization");
        if (header == null || !header.startsWith(BASIC_)) {
            throw new CommonException("请求头中client信息为空");
        }
        return extractAndDecodeHeader(header);
    }

    public static void main(String[] args){
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String encode = passwordEncoder.encode("123456");
        log.info("加密后的密码:" + encode);
        log.info("bcrypt密码对比:" + passwordEncoder.matches("123456", "{bcrypt}$2a$10$NSddA6IOG5Sr9qphtyl8hOHgmHRSbU1zbcnjk4Fr1VvRCOWDXeFA6"));
    }
}